import sqlite3
import requests


class Base:
    remoteBase = "http://127.0.0.1:5000"
    localDatabase = "database.db"
    localTable = ""
    conn = None

    def __init__(self):
        pass

    # Remote server interaction
    @classmethod
    def fetchRemoteContent(self, url):
        resp = requests.get(url)
        return resp

    @classmethod
    def updateRemote(self):
        url = self.getIndexPath()
        resp = self.fetchRemoteContent(url)
        json = resp.json()
        objs = []
        for obj in json:
            objs.append(self.createFromJson(obj))
        for obj in objs:
            self.save(obj)

    # Database interaction
    @classmethod
    def connectToDatabase(self):
        if self.conn is None:
            # Connect to the database
            self.conn = sqlite3.connect(self.localDatabase)

    @classmethod
    def getAll(self):
        self.connectToDatabase()

        c = self.conn.cursor()
        models = []

        # Get the models
        for data in c.execute("SELECT * FROM %s ORDER BY id"
                              % self.localTable):
            models.append(self.createFromRow(data))

        return models

    @classmethod
    def getById(self, idn):
        self.connectToDatabase()

        c = self.conn.cursor()
        c.execute("SELECT * FROM %s WHERE id = ?" % self.localTable, (idn,))
        data = c.fetchone()
        if data:
            return self.createFromRow(data)
        else:
            return None

    @classmethod
    def save(self, object):
        pass
